import os
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles

from ftp_manager import FTPServerManager


app = FastAPI(title="教学FTP服务器管理后台")
manager = FTPServerManager()

# 模板与静态资源目录
templates = Jinja2Templates(directory="templates")
if os.path.isdir("static"):
    app.mount("/static", StaticFiles(directory="static"), name="static")


@app.get("/", response_class=HTMLResponse)
def index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request, "status": manager.status()})


@app.get("/api/status")
def api_status():
    return manager.status()


@app.post("/api/server/start")
async def api_start(params: dict | None = None):
    params = params or {}
    host = params.get("host")
    port = params.get("port")
    manager.start(host, port)
    return manager.status()


@app.post("/api/server/stop")
async def api_stop():
    manager.stop()
    return manager.status()


@app.post("/api/root")
async def api_root(data: dict):
    path = data.get("path")
    if not path:
        raise HTTPException(status_code=400, detail="缺少 path")
    manager.set_root_dir(path)
    return manager.status()


@app.post("/api/users")
async def api_add_user(data: dict):
    username = data.get("username")
    password = data.get("password")
    perm = data.get("perm") or "elradfmwMT"
    if not username or not password:
        raise HTTPException(status_code=400, detail="缺少用户名或密码")
    manager.add_user(username, password, perm)
    return manager.status()


@app.delete("/api/users/{username}")
async def api_del_user(username: str):
    manager.remove_user(username)
    return manager.status()


@app.post("/api/anonymous/enable")
async def api_enable_anon(data: dict | None = None):
    perm = (data or {}).get("perm") or "elr"
    manager.enable_anonymous(perm)
    return manager.status()


@app.post("/api/anonymous/disable")
async def api_disable_anon():
    manager.disable_anonymous()
    return manager.status()


if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)